/**
 * 
 */
package com.kingcore.director.note.dao.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.kingcore.director.DirectorConstants;
import com.kingcore.director.DirectorContext;
import com.kingcore.director.base.dao.impl.DirectorDaoJdbcImpl;
import com.kingcore.director.note.dao.NotePaperDao;

/**
 * @author Zeven
 *
 */
public class NotePaperDaoImpl extends DirectorDaoJdbcImpl implements
				NotePaperDao {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub

	}

	private String tmpFileUri = DirectorContext.getSystemTmpDir() 
			             + File.separator + "notePaper.tmp";
	@Override
	public void updateNotePaper(Object binaryCon) throws Exception {
		if (binaryCon==null) {
			binaryCon = "";
		}
		String sql="UPDATE "+DirectorConstants.NBK_ArticleContent+" SET Contents=?,lastModifiedTime=? " +
								" Where ID="+DirectorConstants.Key_NotePaper_Content ;
		
		log.debug("begin saveNote. tmp file is:"+tmpFileUri);
		File f = new File(tmpFileUri);
		if (!f.exists()) {
			f.createNewFile();
		}
		Connection con = null;
		PreparedStatement pstmt = null;
        ResultSet rs = null;
		ObjectOutputStream out = null;
		try {
			out = new ObjectOutputStream(new FileOutputStream(tmpFileUri));
			out.writeObject(binaryCon);
			FileInputStream ins = new FileInputStream(tmpFileUri);
		
			con = this.getConnection(); 
			pstmt = con.prepareStatement(sql);
			log.debug("-------------"+ins.available());
			pstmt.setBinaryStream( 1, ins , ins.available() );
			pstmt.setString( 2, getSystemTime() );
			
			pstmt.executeUpdate();
			con.commit(); 
			log.debug("Save successfully");
			
        } catch (Exception e) {
            e.printStackTrace();
            wzw.util.DbUtils.closeQuietly(con);
        } finally {
        	try {
            	if (out!=null) out.close(); 
			} catch (Exception e2) {
				e2.printStackTrace();
			}
        	wzw.util.DbUtils.closeQuietly(con, pstmt, rs);
        }

	}


	@Override
	public Object queryNotePaper( ) throws SQLException {
		return queryLargeObject(DirectorConstants.Key_NotePaper_Content, "",
				DirectorConstants.NBK_ArticleContent, "id","Contents");
	}
	
 }